/****************************************************************
**
** This file is part of Music Practice Audio Player
**
** Copyright (C)2012 Serhii Ratsyborynskyi (ratz@live.ru)
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either
** version 2 of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
******************************************************************/

#include "AudioPlayer.hpp"
#include <QDebug>


using namespace AudioCore;

void AudioPlayer::slotPlay()
{
    if(mAudioOutput)
    {
        mAudioOutput->start( mAudioSource );
    }
}

void AudioPlayer::slotStop()
{
    if( mAudioOutput)
    {
    if( mAudioOutput->state() != QAudio::StoppedState)
    {
        mAudioOutput->stop();
    }
    }
}

void AudioPlayer::slotVolume(int volume)
{
    qDebug() << "Volume " << volume << endl;
}

bool AudioPlayer::isReady()
{
    return mState;
}


AudioPlayer::AudioPlayer(QString path, QObject *parent):QObject(parent),
    pAudioDeviceInfo()
{
    mAudioSource= new MPAMixer(path);


    QAudioDeviceInfo audioDeviceInfo =  QAudioDeviceInfo::defaultOutputDevice();
    pAudioDeviceInfo = &audioDeviceInfo;
    mAudioSource->open(QIODevice::ReadOnly);

    Q_CHECK_PTR(mAudioSource);

    if( mAudioSource->isReady() )
    {
        if( audioDeviceInfo.isFormatSupported(mAudioSource->getAudioFormat()))
        {
            qDebug() << "Format Supported";
            qDebug() << "Create audio Output";
            mAudioSource->open(QIODevice::ReadOnly);
            mAudioOutput = new QAudioOutput(pAudioDeviceInfo->defaultOutputDevice(), mAudioSource->getAudioFormat(), this);

            Q_CHECK_PTR(mAudioOutput);
        }
        else
        {
            mState = false;
            qDebug() << "Format not supported";
            qDebug() << "Nearest format choose";


            mAudioOutput = new QAudioOutput( pAudioDeviceInfo->defaultOutputDevice(), pAudioDeviceInfo->nearestFormat( mAudioSource->getAudioFormat() ), this );
        }
    }
}
